<template>
  <div>
    <!-- -----------------------------------------------------基本信息-------------------------------------------------------------- -->
    <el-divider>基本信息</el-divider>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" inline class="rule_form">
      <el-form-item label="设备所属部门" prop="equipmentAccountDictionaryId">
        <el-cascader :disabled="!parenttypeFlag" style="width: 100%;" v-model="ruleForm.equipmentAccountDictionaryId"
          :options="DeptList" placeholder="请选择所属部门"
          :props="{ expandTrigger: 'hover', label: 'deptName', value: 'deptId', checkStrictly: true }"
          @change="handleChange">
        </el-cascader>
      </el-form-item>

      <el-form-item label="设备名称" prop="equipmentAccountId">
        <el-select :disabled="!parenttypeFlag" style="width: 100%;" v-model="ruleForm.equipmentAccountId" filterable
          placeholder="请选择设备" @visible-change="handleChangeEquipmentAccountId">
          <el-option v-for="item in equipmentAccountList" :key="item.equipmentAccountId"
            :label="item.equipmentName + '(' + item.equipmentNum + ')'" :value="item.equipmentAccountId" />
        </el-select>
      </el-form-item>

      <el-form-item label="故障等级" prop="faultLevel">
        <el-select style="width: 100%;" v-model="ruleForm.faultLevel" filterable placeholder="请选择故障等级">
          <el-option v-for="(item, i) in ['紧急', '严重', '一般']" :key="i" :label="item" :value="i" />
        </el-select>
      </el-form-item>

      <el-form-item label="故障类型" prop="faultType">
        <el-select style="width: 100%;" v-model="ruleForm.faultType" multiple placeholder="请选择故障类型">
          <el-option v-for="item in DictionaryList" :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>

      <el-divider>故障描述</el-divider>
      <el-form-item prop="faultDescribe" class="faultDescribe">
        <el-input type="textarea" placeholder="请输入故障描述" :autosize="{ minRows: 4, maxRows: 4}"
          v-model="ruleForm.faultDescribe" maxlength="100" show-word-limit />
      </el-form-item>
      <!-- -----------------------------------------------------附件：异常图片/异常视频-------------------------------------------------------------- -->
      <el-divider>附件：异常图片/异常视频</el-divider>

      <el-form-item label="异常图片" style="width: 100%;">
        <Image-upload :limit="9" :value='ruleForm.repairImages' @input="handleInput" />
      </el-form-item>

      <el-form-item label="异常视频" style="width: 100%;">
        <Video-upload ref="videoUpload" v-model="ruleForm.faultVideo" @returnBack="handleReturnBack" />
      </el-form-item>
      <!-- ---------------------------------------------------委外服务商----------------------------------------------------------- -->
      <el-divider>委外服务商</el-divider>
      <el-form-item label="服务商选定" prop="selectMode">
        <el-select style="width: 100%;" v-model="ruleForm.selectMode" filterable placeholder="请选择服务商"
          @change="handleSelectMode">
          <el-option v-for="(item, i) in ['指定委外服务商','比选委外服务商']" :key="i" :label="item" :value="i" />
        </el-select>
      </el-form-item>

      <el-form-item label="服务商" prop="selectSupplierId" v-if="ruleForm.selectMode == 0" style="width: 100%;">
        <el-select v-model="ruleForm.selectSupplierId" placeholder="请选择服务商" @change="handleSelectSupplier">
          <el-option v-for="item in supplierList" :key="item.supplierId" :label="item.supplierName"
            :value="item.supplierId">
          </el-option>
        </el-select>
      </el-form-item>

      <div class="dialog_table" v-if="ruleForm.selectMode == 1">
        <el-button style="margin: 0 0 40px 26px;" type="primary" icon="el-icon-plus" @click="handleSubmitSupplier">
          添加比选服务商</el-button>
        <el-table :data="ruleForm.supplierCompares" max-height="550px" style="width: 100%">
          <el-table-column label="序号" width="100">
            <template slot-scope="scope">
              <div> {{ scope.$index + 1 }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="supplierName" label="供应商名称" width="160" />
          <el-table-column prop="addr" label="地址" />
          <el-table-column prop="liaison" label="联系人" />
          <el-table-column prop="phone" label="联系电话" show-overflow-tooltip>
            <template slot-scope="{row}">
              <div> {{ row.phone || '-' }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="website" label="官网" show-overflow-tooltip>
            <template slot-scope="{row}">
              <div> {{ row.website || '-' }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="file" label="附件">
            <template slot-scope="scope">
              <el-link :disabled="!(scope.row.file)" icon="el-icon-document" type="primary" :href=" scope.row.file"
                target="_blank">
                附件资料</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="服务商特点描述" min-width="90">
            <template slot-scope="scope">
              <el-form-item :prop="'supplierCompares.' + scope.$index + '.description'" :rules="rules.description"
                style="margin-top:18px ;">
                <el-input type="textarea" autosize v-model="scope.row.description" placeholder="请输入服务商特点描述" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right">
            <template slot-scope="scope">
              <el-button size="small" type="primary" icon="el-icon-view" @click="handleSelectImage(scope.row.image)">图片
              </el-button>
              <el-button size="small" icon="el-icon-delete" type="danger" @click="handledelete(scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-divider>比选结果</el-divider>

        <div style="width:1000px ;">
          <div style="margin:0 0 15px 30px;color: red;font-size: 12px;">注：审核通过后，新服务商将自动加入供应商管理模块中
          </div>
          <el-form-item label="选定服务商" prop="selectSupplierName" style="width: 100%;">
            <el-select style="width: 400px;" v-model="ruleForm.selectSupplierName" placeholder="请选择服务商"
              @change="handleSelectSupplier">
              <el-option v-for="item in ruleForm.supplierCompares" :key="item.supplierName" :label="item.supplierName"
                :value="item.supplierName">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选定原因" prop="selectSupplierReason">
            <el-input style="width: 400px;" type="textarea" placeholder="请输入选定原因" :autosize="{ minRows: 4, maxRows: 4}"
              v-model="ruleForm.selectSupplierReason" maxlength="100" show-word-limit />
          </el-form-item>
        </div>
      </div>
      <!-- ---------------------------------------------------附件信息----------------------------------------------------------- -->
      <el-divider>附件信息</el-divider>
      <el-form-item label="图片" style="width: 100%;">
        <Image-upload :limit="9" :value='ruleForm.images' @input="handleimagesInput" />
      </el-form-item>

      <el-form-item label="附件" style="width: 100%;">
        <FileUpload v-model="ruleForm.files" :limit="5" :fileSize="50"
          :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
        </FileUpload>
      </el-form-item>
      <!-- ---------------------------------------------------审核信息----------------------------------------------------------- -->
      <el-divider>审核信息</el-divider>
      <div class="rule_form_audit">
        <el-form-item label="审核人" prop="auditVosUser">
          <el-select v-model="ruleForm.auditVosUser" collapse-tags multiple placeholder="请选择审核人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="" style="margin-left:120px">
          <span v-for="(tag, index) in tagUserList" :key="index">
            <el-tag closable disable-transitions @close="tagChange(tag, index)">
              <span>{{ tag.name }}</span>
            </el-tag>
            <span style="font-size:28px;position: relative;top: 5px;">
              <template v-if="index !== tagUserList.length - 1">
                <i class="el-icon-caret-right"></i>
              </template>
            </span>
          </span>

        </el-form-item>
        <el-form-item label="抄送人">
          <el-select v-model="ruleForm.auditVosType" multiple placeholder="请选择抄送人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
    </el-form>
    <template v-if="ImageOpen">
      <Dialog-image :src="imageSrc" />
    </template>
    <supplier v-if="supplierFlag" @click_close="()=>supplierFlag =false" @submit_success="handleSubmitSuccess">
    </supplier>
    <Dialog-image v-if="ImageOpen" :src="imageSrc" />
    <!-- ---------------------------------------------------提交及取消【按钮】----------------------------------------------------------- -->
    <div class="form_btn">
      <el-button type="primary" @click="handleSubmitForm">提交</el-button>
      <el-button @click="handleCloseForm">取消</el-button>
    </div>
  </div>
</template>

<script>
import { listEquipmentAccount, listDictionary, add, listDept, supplierlist, getuserlist, listDetail, addapply, listAccount } from '@/api/maintenance/management/Outsourcing.js'
import supplier from './supplier.vue'
/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  equipmentAccountDictionaryId: null, // 部门id，只做下一步操作，===>不做表单数据
  equipmentAccountId: null, //设备ID
  faultLevel: null,//故障等级
  faultType: [], //故障类型
  faultDescribe: "", //故障描述
  repairImages: [], //异常图片集合
  faultVideo: "", //异常视频
  selectMode: 0,//服务商选定（0比选委外服务商 1指定委外服务商）
  selectSupplierName: '',//0比选委外服务商的选定服务商名称
  selectSupplierId: null,//1指定委外服务商的供应商ID
  selectSupplierReason: '',//选定供应商的原因
  supplierCompares: [],// 服务商列表数据展示
  images: [],//图片集合
  files: '',//附件
  auditVosUser: [],// 审核人
  auditVosType: []// 抄送人
}

/** ---------------------------------------------------------------------------------------------------------------------------------- */

// 表单参数处理重组------------------------
function processQueryParams (data) {
  const paramsFaultLevel = data.faultType.join(',') //故障级别
  const paramsRepairImages = data.repairImages.map(item => { //故障图片
    return {
      image: item.url
    }
  })
  let paramsImages = []
  console.log(data);
  if (data.images) {
    paramsImages = data.images.map(item => item.url).join(',') //图片
  } else {
    paramsImages = data.images //图片
  }
  let paramsSupplierCompares = []
  if (data.selectMode) {
    paramsSupplierCompares = data.supplierCompares.map(item => {//比对供应商信息
      return {
        supplierFrom: item.supplierFrom,
        supplierName: item.supplierName,
        address: item.addr,
        contact: item.liaison,
        telephone: item.phone,
        website: item.website,
        image: item.image,
        file: item.file,
        remark: item.remark,
        description: item.description,
      }
    })
  }
  const examine = data.auditVosUser.map(item => {
    return {
      userId: item,
      userType: 0
    }
  })//审核人
  const copy = data.auditVosType.map(item => {
    return {
      userId: item,
      userType: 1
    }
  })// 抄送人
  let params = {
    repairVo: {
      equipmentAccountId: data.equipmentAccountId,
      faultVideo: data.faultVideo,
      faultDescribe: data.faultDescribe,
      faultLevel: data.faultLevel,
      faultType: paramsFaultLevel,
      repairImages: paramsRepairImages
    },
    images: paramsImages,
    supplierCompares: paramsSupplierCompares,
    auditVos: examine.concat(copy),
    files: data.files,
    selectMode: data.selectMode,
    compareId: data.selectSupplierId,
    selectSupplierName: data.selectSupplierName,
    selectSupplierReason: data.selectSupplierReason,
    outsourceId: data.outsourceId || ''
  }
  return params
}

export default {
  name: 'detailedform',
  components: {
    supplier
  },
  data () {
    return {
      ruleForm,
      formFLag: false,
      imageSrc: undefined,//图片预览参数
      ImageOpen: false,
      allUserData: [],//用户信息列表
      DeptList: [], // 部门数组
      DictionaryList: [], // 故障类型数组
      equipmentAccountList: [],//设备名称接收数组
      supplierList: [],//服务商数组
      supplierFlag: false,//比选服务商弹框开关
      ImageOpen: false,
      imageSrc: undefined,
      parenttypeFlag: true,//重新申请和新增共用一个开关，用于和申请的接口区分
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        equipmentAccountDictionaryId: [
          { required: true, message: '请选择部门', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        equipmentAccountId: [
          { required: true, message: '请选择设备', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultLevel: [
          { required: true, message: '请选择故障等级', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultDescribe: [
          { required: true, message: '请输入故障描述', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        repairImages: [
          { required: true, message: '请上传故障图片', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultType: [
          { required: true, message: '请选择故障类型', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        selectMode: [
          { required: true, message: '请选定服务商', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        selectSupplierName: [
          { required: true, message: '请选择服务商', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        selectSupplierId: [
          { required: true, message: '请选择服务商', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入服务商特点描述', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        selectSupplierReason: [
          { required: true, message: '请输入选定服务商原因', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        auditVosUser: [
          { required: true, message: '请选择审核人', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        auditVosType: [
          { required: true, message: '请选择抄送人', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  computed: {
    // 审核人数据转换--------------------------
    tagUserList () {
      let Arr = []
      this.ruleForm.auditVosUser.map(item => {
        this.allUserData.map(value => {
          if (item === value.userId) {
            Arr.push({
              userId: value.userId,
              name: value.userName
            })
          }
        })
      })
      return Arr
    },
  },

  methods: {
    // 设备所属部门和设备名称 数据接口---------------------------------------------
    async handleListType () {
      const { data: res1 } = await listDept({ status: 0 })//部门列表
      this.DeptList = this.handleTree(res1, 'deptId')
      const { data: res2 } = await listDictionary({ dictType: 'fault_type', status: 0 })//故障类型，字典单位
      const { data: res3 } = await supplierlist()
      const { data: res4 } = await getuserlist();
      this.DictionaryList = res2
      this.supplierList = res3
      this.allUserData = res4
    },

    // 点击列表【重新申请】按钮，【提交/撤销】按钮的【申请】按钮
    handleParentint (value) {
      this.handleListType();
      if (value) {
        listDetail(value.id).then(res => {
          listDept({ status: 0 }).then(res1 => {
            const rule = this.getParentIdList(this.handleTree(res1.data, 'deptId'), res.data.repairVo.repairEquipmentAccountVo.eaPartInfoVo.deptId, { id: 'deptId' })
            this.ruleForm.equipmentAccountDictionaryId = rule
            this.handleChange(rule);
            this.ruleForm.equipmentAccountId = res.data.repairVo.repairEquipmentAccountVo.eaPartInfoVo.equipmentAccountId * 1;
          })
          this.ruleForm.faultLevel = res.data.repairVo.faultLevel * 1;
          this.ruleForm.faultType = res.data.repairVo.faultType.split(',');
          this.ruleForm.faultDescribe = res.data.repairVo.faultDescribe;
          this.ruleForm.faultVideo = res.data.repairVo.faultVideo;
          this.ruleForm.repairImages = res.data.repairVo.repairImages.filter(item => item.type == 0).map(item => item.image || '') || [];
          // -----------------------------------------------------------------------------------------
          this.ruleForm.selectMode = res.data.selectMode * 1;
          this.ruleForm.selectSupplierId = res.data.compareId * 1 || '';
          console.log(res);
          this.ruleForm.selectSupplierReason = res.data.selectSupplierReason;
          this.ruleForm.selectSupplierName = res.data.supplierCompares?.filter(item => item.compareId == res.data.compareId)[0].supplierName
          console.log(res.data);
          this.ruleForm.images = res.data.images?.split(',').map(item => {
            return {
              url: item
            }
          });
          this.ruleForm.repairImages = res.data.repairVo?.repairImages.map(item => {
            return {
              url: item.image
            }
          })
          this.ruleForm.supplierCompares = res.data.supplierCompares?.map(item => {
            return {
              ...item,
              addr: item.address,
              liaison: item.contact,
              phone: item.telephone,
            }
          })
          this.ruleForm.files = res.data.files;
          this.$set(this.ruleForm, 'outsourceId', res.data.outsourceId)
          if (value.type) {
            //【提交/ 撤销】的【申请】操作
            this.parenttypeFlag = false
          } else {
            // 【重新申请】操作
            this.parenttypeFlag = true
          }
        })
      } else {
        // 【新增委外】操作
        this.parenttypeFlag = true
      }
    },

    // 设备所属部门选择事件---------------------------------
    handleChange (arr) {
      this.ruleForm.equipmentAccountId = null
      const id = arr.slice(-1).join()
      listEquipmentAccount({ 'params[userStatuses]': this.parenttypeFlag ? '0,1,2,4' : '0,1,2,3,4,5', 'params[statuses]': this.parenttypeFlag ? '0,3' : '0,1,2,3', 'params[flag]': 'N', 'params[deptIds]': id }).then(({ data: res }) => {
        this.equipmentAccountList = res
        console.log(this.equipmentAccountList);
      })//设备名称
    },
    // 设备所属部门选择事件-------------
    handleChangeEquipmentAccountId (flag) {
      if (flag) {
        if (!this.ruleForm.equipmentAccountDictionaryId) {
          this.$message.error('请选择设备所属部门');
        } else {
          return
        }
      } else {
        return false
      }
    },

    // 服务商选定操作事件-----------
    handleSelectMode () {
      this.ruleForm.selectSupplierId = null;
      this.ruleForm.supplierCompares = [];
    },
    handleSubmitSupplier () {
      this.supplierFlag = true
    },
    // 添加比选服务商传上来的数据
    handleSubmitSuccess (val) {
      this.supplierFlag = false
      let arr = []
      if (val.faultLevel) {
        let supplier = Object.assign({ supplierFrom: 1 }, val.supplierObj);
        arr = [...this.ruleForm.supplierCompares, supplier]
      } else {
        let supplier = val.supplierIdList.map(item => {
          return {
            ...item,
            supplierFrom: 2
          }
        })
        arr = [...this.ruleForm.supplierCompares, ...supplier]
      }
      this.ruleForm.supplierCompares = this.removedup(arr, 'supplierName')
    },
    // 上传图片处理方法-----------------
    handleInput (val) {
      this.ruleForm.repairImages = val
    },
    handleimagesInput (val) {
      this.ruleForm.images = val
    },
    // 上传视频处理方法--------------------
    handleReturnBack (val) {
      this.ruleForm.faultVideo = val
    },
    // 服务商选择事件-----------------------------------------
    handleSelectSupplier (id) {
      const rule = this.supplierList.filter(item => item.supplierId == id).map(item => item.liaison + '（' + item.phone + '）').join()
      this.ruleForm.supplierTitle = rule
    },
    // ----------添加采购品【按钮】 ------------------
    handleAddPurchase () {
      this.$refs['purchase_form'].openDialog(this.ruleForm.type)
    },
    // 表单采购类型选择器切换
    handleOptions () {
      this.ruleForm.supplierCompares = []
    },
    // 接收子组件勾选后的数据
    // handleSlectList (val) {
    //   console.log(val);
    //   const arr = [...this.ruleForm.supplierCompares, ...val];
    //   this.ruleForm.supplierCompares = this.removedup(arr, this.ruleForm.type == 0 ? 'equipmentBaseId' : 'consumableBaseId');
    // },
    // fn2 (arr) {
    //   const res = new Map();
    //   return arr.filter(arr => !res.has(arr.consumableBaseId) && res.set(arr.consumableBaseId, arr.consumableBaseId));
    // },

    //列表的查看图片事件
    handleSelectImage (src) {
      this.imageSrc = src
      this.ImageOpen = true
    },
    //列表的删除事件
    handledelete (index) {
      this.ruleForm.supplierCompares.splice(index, 1)
    },
    // 审核人删除事件
    tagChange (val, index) {
      this.ruleForm.auditVosUser.splice(index, 1)
    },
    // 表单总提交事件
    handleSubmitForm () {
      // console.log('Form总提交数据',this.ruleForm);
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.ruleForm.repairImages.length || this.ruleForm.faultVideo) {
            console.log('最终数据', this.ruleForm);
            const form = processQueryParams(this.ruleForm)
            if (this.parenttypeFlag) {
              add(form).then(() => {
                this.$emit('form_submit_click')
                this.$message.success('申请委外维修成功！');
                this.handleRemove();
              })
            } else {
              addapply(form).then(() => {
                this.$emit('form_submit_click')
                this.$message.success('申请委外维修成功！');
                this.handleRemove();
              })
            }

          } else {
            this.$message({
              message: '请上传异常图片或者异常视频！',
              type: 'error'
            })
          }
        } else {
          this.$message.error('提交表单验证信息不通过，请重新输入');
        }
      })
    },
    handleRemove () {
      for (const k in this.ruleForm) {
        this.ruleForm[k] = ''
      }
      this.ruleForm.type = '0'
      this.ruleForm.supplierCompares = []
      this.ruleForm.auditVosUser = []
      this.ruleForm.auditVosType = []
    },
    // 表单取消事件
    handleCloseForm () {
      this.handleRemove()
      this.$emit('form_submit_click')
    },
    // 查看图片
    handleSelectImage (src) {
      this.imageSrc = src
      this.ImageOpen = true
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog_table {
  margin-top: 20px;
}

.faultDescribe {
  width: 100%;

  ::v-deep .el-form-item__content {
    width: 100%;
  }
}


/* el-descriptions-item 文字居中 */
::v-deep .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
  text-align: center;
}

.rule_form_audit {
  width: 26%;
  margin: auto;
}

.dialog_btn {
  margin: 10px 45px;
}



.form_btn {
  width: 42%;
  display: flex;
  justify-content: center;
  margin: 50px auto 20px auto;
}
</style>